package cn.bbstone.pisces2.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.osgi.service.component.annotations.Component;

import cn.bbstone.pisces2.cmm.Pi2ContextUtil;
import cn.bbstone.pisces2.cmm.UIConst;
import cn.bbstone.pisces2.comm.fli.FliIndex;
import cn.bbstone.pisces2.model.FileListItem;
import cn.bbstone.pisces2.service.FileListService;
import cn.bbstone.pisces2.util.FLIUtil;

@Component
public class FileListServiceImpl implements FileListService {

	
//	private int count = 0;

	@Override
	public void loadAll(List<FileListItem> targetList) {
		targetList.clear();

		int pageSize = 10;
		long count = 0L;
		// load server file list(~/.fli_server/fli.idx)
		if (UIConst.RUN_AS_SERVER.equals(Pi2ContextUtil.getRunAs())) {
			count = FLIUtil.getServerIndexCount();
			if (count > pageSize) {
				long start = 0L;
				while(start <= count) {
					List<FliIndex> linesFliIndexs = FLIUtil.readServerIndexLines(start, pageSize);
					linesFliIndexs.stream().forEach(e -> targetList.add(convertToFileListItem(e)));
					start += pageSize;
				}
			}
		}

		// load server file list(~/.fli_client/fli.idx)
		if (UIConst.RUN_AS_CLIENT.equals(Pi2ContextUtil.getRunAs())) {
			count = FLIUtil.getClientIndexCount();
			
			
		}


//		List<FliIndex> linesFliIndexs = FLIUtil.readServerAllIndexLines();
//		linesFliIndexs.stream().forEach(e -> fileListItems.add(convertToFileListItem(e)));

//		String fileRPath  = "/workspaceBizSD/.metadata/.plugins/org.eclipse.jdt.core/1019992399.index";
//		String dirRPath = "/workspaceBizSD/.metadata/.plugins/org.eclipse.jdt.core/";
//		for (int i = 0; i < 10; i++) {
//			FileListItem item = new FileListItem();
//			item.setFileNo(i + 1);
//			item.setFileCat(i%2 == 0 ? "D" : "F");
//			item.setRpath(i%2 == 0 ? dirRPath : fileRPath);
//			fileListItems.add(item);
//		}
//		return fileListItems;
	}

	private FileListItem convertToFileListItem(FliIndex index) {
		FileListItem item = new FileListItem();
		item.setFileNo(index.getFileNo());
		item.setFileCat(index.getFileCat());
		item.setRpath(index.getRpath());
		return item;
	}

	@Override
	public List<FileListItem> loadPage(long start, int pageSize) {
		List<FileListItem> fileListItems = new ArrayList<>();
		List<FliIndex> linesFliIndexs = FLIUtil.readServerIndexLines(start, pageSize);
		linesFliIndexs.stream().forEach(e -> fileListItems.add(convertToFileListItem(e)));
		
		return fileListItems;
	}
	@Override
	public List<FileListItem> loadClientPage(long start, int pageSize) {
		List<FileListItem> fileListItems = new ArrayList<>();
		List<FliIndex> linesFliIndexs = FLIUtil.readClientIndexLines(start, pageSize);
		linesFliIndexs.stream().forEach(e -> fileListItems.add(convertToFileListItem(e)));
		
		return fileListItems;
	}

//	public int itemCount() {
//		count = (int) FLIUtil.getServerIndexCount();
//		return count;
//	}

}
